<template>
    <div class="SearchPage">
        <!-- 顶部功能区 -->
        <div class="header">
            <!-- 返回按钮 -->
            <img src="@/assets/img/arrow-left.svg" alt="" @click="$router.back()">
            <!-- 搜索框 -->
            <form action="/">
                <van-search
                    v-model="value"
                    shape="round"
                    placeholder="请输入搜索关键词"
                    @input="onSearch"
                />
            </form>
            <!-- 搜索按钮 -->
            <span @click="onSearch(value)">搜索</span>
        </div>
        <!-- 搜索结果 -->
        <div class="result">
            <div class="item" v-for="(e, i) in list" :key="i">
                <img src="@/assets/img/btn_search.svg" alt="">
                <!-- 不能用插值表达式 -->
                <div v-html="e"></div>
            </div>
        </div>
    </div>
</template>

<script>
import { getSuggestion } from '@/api/search'

export default {
    name: 'SearchPage',
    data () {
        return {
            value: '',
            list: []
        }
    },
    methods: {
        async onSearch (val) {
            if (val) {
                const res = await getSuggestion(val)
                this.list = res.data.data.options.map(e => {
                    // 1. 用split方法将字符串用搜索关键字拆分
                    // 2. 用join方法将加工好的关键字拼接
                    return e.split(this.value).join(`<span class="keywords">${ this.value }</span>`)
                })
            } else {
                this.list = []
            }
        }
    }
}
</script>

<style scoped lang="less">
.SearchPage {
    .header {
        display: flex;

        > img {
            width: 16px;
            margin-left: 10px;
        }

        > form {
            flex: 1;

            ::v-deep .van-search__action {
                padding: 0 10px;
            }
        }

        span {
            color: #343434;
            display: block;
            width: 30px;
            font-size: 14px;
            line-height: 52px;
            padding: 0 8px 0 0;
        }
    }

    .result {
        padding: 0 14px;
        font-size: 16px;

        .item {
            display: flex;
            align-items: center;
            margin: 20px 0;

            img {
                width: 14px;
                margin-right: 10px;
            }

            ::v-deep .keywords {
                color: #FC6627;
            }
        }
    }
}
</style>
